<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\admin;

use app\common\model\MemberPluginOrder;
use app\common\model\Plugin;
use buwang\base\AdminBaseController;
use buwang\traits\Crud;
use think\facade\View;

class MemberMiniapp extends AdminBaseController
{
    use Crud;

//    protected $middleware = [
//        'login' 	=> ['except' 	=> [] ]
//    ];
    protected $model = null;//模型实例

    protected function initialize()
    {
        parent::initialize();

        $this->model = new \app\common\model\MemberMiniapp();
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $status = request()->get('status/s');
            $miniapp_id = request()->get('miniapp_id/d');
            $userId      = $this->request->param('userId', NULL);
            $appName     = $this->request->param('appName', NULL);
            $expireStart = $this->request->param('expireStart', NULL);
            $expireEnd   = $this->request->param('expireEnd', NULL);
            if (input('selectFieds')) {
                return $this->selectList();
            }
            $this->relationSearch = true;
            list($page, $limit, $where) = $this->buildTableParames();
            if (isset($userId)) {
                $where[] = ['member_id', '=', $userId];
            }
            if (isset($appName)) {
                $where[] = ['appname', 'like', "%$appName%"];
            }
            if (isset($expireStart)) {
                $where[] = ['expire_time', '>=', $expireStart];
            }
            if (isset($expireEnd)) {
                $where[] = ['expire_time', '<=', $expireEnd];
            }

            if (isset($miniapp_id)) {
                $where[] = ['miniapp_id', '=', $miniapp_id];
            }

            if (isset($status) && $status !== '') {
                //正常
                if ($status == 0) {
                    $where[] = ['is_lock', '=', 0];
                    $where[] = ['expire_time', '>', time()];
                }
                //锁定
                if ($status == 1) {
                    $where[] = ['is_lock', '=', 1];
                }
                //即将过期：30天后要过期的
                if ($status == 2) {
                    $where[] = ['expire_time', '<=', time() + 2592000];
                    $where[] = ['expire_time', '>', time()];
                }
                //已过期
                if ($status == 3) {
                    $where[] = ['expire_time', '<=', time()];
                }
            }
            //全部
            $all_count = $this->model->count();
            //正常
            $normal_count = $this->model
                ->where('is_lock', '=', 0)
                ->where('expire_time', '>', time())
                ->count();
            //锁定
            $lock_count = $this->model
                ->where('is_lock', '=', 1)
                ->count();
            //即将过期：30天后要过期的
            $will_expire_count = $this->model
                ->where('expire_time', '<=', time() + 2592000)
                ->where('expire_time', '>', time())
                ->count();
            //已过期
            $expire_count = $this->model
                ->where('expire_time', '<=', time())
                ->count();

            $count = $this->model
                ->with(['Member', 'Miniapp'])
                ->where($where)
                ->count();
            $list = $this->model
                ->with(['Member', 'Miniapp'])
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();

            if ($list) {
                $memberIds = [];
                foreach ($list as $detail) {
                    //插件订单
                    $plugin_count = MemberPluginOrder::where('member_id', $detail['member_id'])
                        ->where('member_miniapp_id', $detail['id'])
                        ->count();
                    $detail['plugin_count'] = $plugin_count;
                    if (!strstr($detail['Miniapp']['logo_image'], 'http')) {
                        $detail['Miniapp']['logo_image'] = bw_config('web_config.web_url') . '/' . $detail['Miniapp']['logo_image'];
                    }
                    $memberIds[ $detail['member_id'] ] = 1;
                }
                $memberNameMap = $this->_getMemberNames(array_keys($memberIds));
                foreach ($list as &$line) {
                    if (isset($memberNameMap[ $line['member_id'] ])) {
                        $line['member_name'] = $memberNameMap[ $line['member_id'] ];
                    } else {
                        $line['member_name'] = '已删除';
                    }
                }
            }
            $data = [
                'total' => $count,
                'list' => $list,
                'all_count' => $all_count,
                'normal_count' => $normal_count,
                'lock_count' => $lock_count,
                'will_expire_count' => $will_expire_count,
                'expire_count' => $expire_count,
            ];
            return $this->success('success', $data);
        }
        //搜索条件
        $where = [];
        $miniapp_id = request()->param('miniapp_id/d', 0);
        if ($miniapp_id !== 0) $where['miniapp_id'] = $miniapp_id;
        View::assign(compact('where'));
        return view();
    }

    protected function _getMemberNames(array $ids):array {
        $records = \app\common\model\Member::whereIn('id', $ids)
            ->select();
        $map     = [];
        if (is_iterable($records)) {
            foreach ($records as $record) {
                $map[ $record->id ] = $record->nickname;
            }
        }

        return $map;
    }
    /**
     * 编辑
     * @menu true
     * @param int $id
     */
    public function edit($id = 0)
    {
        $row = $this->model->find($id);
        if (request()->isPost()) {
            if (!$row) return $this->error('记录不存在');

            $param = request()->post();
            //TODO 参数验证

            $this->model->startTrans();
            try {
                //TODO 更新记录
                $row->save($param);
                $this->model->commit();
            } catch (\Exception $e) {
                $this->model->rollback();
                return $this->error('编辑失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success('编辑成功');
        }

        if (!$row) return $this->error_jump('记录不存在');

        View::assign('row', $row);
        return view();
    }

}
